﻿using Common.Untils;
using HandyControl.Controls;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.IO;
using System.Text.Json;
using System.Windows.Media;
using System.Threading.Tasks;
using System.Windows;
using System.Diagnostics;
using System.Reflection;
using MessageBox = HandyControl.Controls.MessageBox;
using System.Collections.ObjectModel;
using System.Linq;
using Tryit.Services;

namespace Tryit.ViewModels
{
    public class SettingsViewModel : BindableBase
    {
        private bool _isAutoStart;
        private int _databaseBackupDay = 1;
        private readonly string _configPath;
        private bool _isDirty;
        private readonly DatabaseBackupService _backupService;

        public ObservableCollection<int> BackupDays { get; }

        public bool IsAutoStart
        {
            get => _isAutoStart;
            set
            {
                if (SetProperty(ref _isAutoStart, value))
                {
                    IsDirty = true;
                }
            }
        }

        public int DatabaseBackupDay
        {
            get => _databaseBackupDay;
            set
            {
                if (SetProperty(ref _databaseBackupDay, value))
                {
                    IsDirty = true;
                }
            }
        }

        public bool IsDirty
        {
            get => _isDirty;
            set => SetProperty(ref _isDirty, value);
        }

        public DelegateCommand SaveSettingsCommand { get; }
        public DelegateCommand ManualBackupCommand { get; }

        public SettingsViewModel()
        {
            _configPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "SanmaoTools",
                "settings.json"
            );

            _backupService = new DatabaseBackupService();

            // 初始化备份日期选项（1-28）
            BackupDays = new ObservableCollection<int>(Enumerable.Range(1, 28));
            
            SaveSettingsCommand = new DelegateCommand(ExecuteSaveSettings);
            ManualBackupCommand = new DelegateCommand(async () => await ExecuteManualBackup());
            LoadSettings();
        }

        private async Task ExecuteManualBackup()
        {
            try
            {
                await _backupService.ManualBackupAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Error($"备份失败：{ex.Message}", "错误");
            }
        }

        private void LoadSettings()
        {
            try
            {
                if (File.Exists(_configPath))
                {
                    var json = File.ReadAllText(_configPath);
                    var settings = JsonSerializer.Deserialize<Settings>(json);
                    _isAutoStart = settings.IsAutoStart;
                    _databaseBackupDay = settings.DatabaseBackupDay;
                }

                // 检查开机自启动状态
                string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
                string appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
                string shortcutPath = Path.Combine(startupPath, $"{appName}.lnk");
                bool shortcutExists = File.Exists(shortcutPath);
                
                if (shortcutExists != _isAutoStart)
                {
                    _isAutoStart = shortcutExists;
                    SaveSettings();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"加载设置失败: {ex.Message}");
            }
        }

        private void SaveSettings()
        {
            try
            {
                var settings = new Settings
                {
                    IsAutoStart = _isAutoStart,
                    DatabaseBackupDay = _databaseBackupDay
                };

                var json = JsonSerializer.Serialize(settings, new JsonSerializerOptions
                {
                    WriteIndented = true
                });

                Directory.CreateDirectory(Path.GetDirectoryName(_configPath));
                File.WriteAllText(_configPath, json);
                IsDirty = false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"保存设置失败: {ex.Message}");
            }
        }

        private void ExecuteSaveSettings()
        {
            if (_isAutoStart)
            {
                SetStartUp();
            }
            else
            {
                RemoveStartUp();
            }
            SaveSettings();
            MessageBox.Success("设置已保存", "成功");
        }

        private void SetStartUp()
        {
            try
            {
                var shellType = Type.GetTypeFromProgID("WScript.Shell");
                dynamic shell = Activator.CreateInstance(shellType);
                string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
                string appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
                string shortcutPath = Path.Combine(startupPath, $"{appName}.lnk");
                
                if (File.Exists(shortcutPath))
                {
                    File.Delete(shortcutPath);
                }

                string exePath = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    "SanmaoTools.exe"
                );

                if (!File.Exists(exePath))
                {
                    throw new FileNotFoundException($"找不到可执行文件: {exePath}");
                }

                var shortcut = shell.CreateShortcut(shortcutPath);
                shortcut.TargetPath = exePath;
                shortcut.WorkingDirectory = Path.GetDirectoryName(exePath);
                shortcut.Description = "SanmaoTools开机自启动";
                shortcut.Save();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"设置开机自启动失败: {ex.Message}");
                MessageBox.Error($"设置开机自启动失败: {ex.Message}", "错误");
                IsAutoStart = false;
            }
        }

        private void RemoveStartUp()
        {
            try
            {
                string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
                string appName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
                string shortcutPath = Path.Combine(startupPath, $"{appName}.lnk");
                
                if (File.Exists(shortcutPath))
                {
                    File.Delete(shortcutPath);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"取消开机自启动失败: {ex.Message}");
                IsAutoStart = true;
            }
        }
    }

    public class Settings
    {
        public bool IsAutoStart { get; set; }
        public int DatabaseBackupDay { get; set; } = 1; // 默认每月1号备份
    }
}
